package com.test.websample.controller;

import com.test.websample.utils.JwtUtil;
import com.test.websample.utils.Util;
import com.test.websample.pojo.Result;
import com.test.websample.pojo.User;
import com.test.websample.service.UserService;
import jakarta.validation.constraints.Max;
import jakarta.validation.constraints.NotEmpty;
import jakarta.validation.constraints.Pattern;
import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.UUID;

@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    UserService userService;

    @PostMapping("/register")
    public Result register(@RequestBody @Validated(RegisterValidGroup.class) UserRegisterBody userRegisterBody, BindingResult bindingResult) {
        // check params
        if (bindingResult.hasErrors()) {
            // 校验失败，构造自定义错误信息
            StringBuilder errorMessage = new StringBuilder();
            bindingResult.getAllErrors().forEach(error -> errorMessage.append(error.getDefaultMessage()).append("; "));
            return Result.error(errorMessage.toString());
        }
        // check user exists
        User user = userService.getUserByName(userRegisterBody.getName());
        if (user != null) {
            return Result.error("用户名已存在");
        }
        // add new user
        User newUser = new User();
        newUser.setName(userRegisterBody.getName());
        newUser.setAge(userRegisterBody.getAge());
        newUser.setAlive(true);
        newUser.setPassword(Util.getMD5Hash(userRegisterBody.getPassword()));
        userService.addUser(newUser);
        return Result.success();
    }

    @PostMapping("/login")
    public Result login(@RequestBody @Validated UserLoginBody loginBody) {
        // check user exists
        User user = userService.getUserByName(loginBody.getName());
        if (user == null) {
            return Result.error("用户不存在");
        }
        // check password
        if (!Util.getMD5Hash(loginBody.getPassword()).equalsIgnoreCase(user.getPassword())) {
            return Result.error("密码错误");
        }
        return Result.success(JwtUtil.genJwt(new HashMap<String, Object>(){{
            put("name", loginBody.getName());
            put("id", user.getId());
        }}));
    }

    @PostMapping("/uploadHeaderFile")
    public Result uploadHeaderFile(MultipartFile file) throws IOException {
        String name = file.getOriginalFilename();
        if (name == null) {
            return Result.error("文件名为空");
        }
        String uuid = UUID.randomUUID().toString() + name.substring(name.lastIndexOf("."));
        String filePath = "/Users/tianpangpang/code/Java/springframework/spring-code/web-sample/ass/" + uuid;
        file.transferTo(new File(filePath));
        return Result.success("out put path : " + filePath);
    }

    @Data
    public static class UserRegisterBody {
        @Pattern(regexp = "^[a-zA-Z0-9_]{2,20}$", message = "用户名只能包含数字、字母和下划线", groups = RegisterValidGroup.class)
        private String name;
        @Max(value = 100, message = "年龄不能超过100岁")
        private int age;
        @Pattern(regexp = "^[a-zA-Z0-9_]{5,20}$", message = "密码只能包含数字、字母和下划线，且不能少于5位")
        private String password;
    }

    @Data
    public static class UserLoginBody {
        @NotEmpty
        private String name;
        @NotEmpty
        private String password;

    }

    public interface RegisterValidGroup{}
}
